package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.RecommendUserApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.mapper.UserInfoMapper;
import com.tanhua.mapper.UserMapper;
import com.tanhua.pojo.TodayBest;
import com.tanhua.pojo.User;
import com.tanhua.pojo.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class TodayBestService {

    @Autowired
    private UserService userService;

    @Reference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${tanhua.sso.default.user}")
    private Integer defaultId;

    public TodayBest queryTodayBest(String token) {

        User user = userService.queryUserByToken(token);

        if (null == user) {
            //token已经失效
            return null;
        }

        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(user.getId());
//        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(1L);//测试

        TodayBest todayBest = new TodayBest();
        UserInfo userInfo;

        if (recommendUser == null) {
            //如果没有今日佳人, 则推荐配置文件中的默认推荐用户
            todayBest.setId(Long.valueOf(defaultId));
            //设置缘分值固定为80
            todayBest.setFateValue(80L);
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",defaultId);
            userInfo = userInfoMapper.selectOne(queryWrapper);
        } else {
            userInfo = userInfoMapper.selectById(recommendUser.getUserId());
            if (null == userInfo){
                return null;
            }
            todayBest.setId(Long.valueOf(userInfo.getUserId()));
            todayBest.setFateValue(recommendUser.getScore().longValue());
        }

        todayBest.setAge(userInfo.getAge());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(StringUtils.equals("1", userInfo.getSex().toString()) ? "man" : "woman");
        todayBest.setTags(userInfo.getTags().split(","));

        return todayBest;
    }
}
